# coding=utf8
from StringIO import StringIO

from PIL import Image, ImageFilter

pdf = file("IMG.pdf", "rb").read()

startmark = "\xff\xd8"
startfix = 0
endmark = "\xff\xd9"
endfix = 2
i = 0

njpg = 0
while True:
    istream = pdf.find("stream", i)
    if istream < 0:
        break
    istart = pdf.find(startmark, istream, istream + 20)
    if istart < 0:
        i = istream + 20
        continue
    iend = pdf.find("endstream", istart)
    if iend < 0:
        raise Exception("Didn't find end of stream!")
    iend = pdf.find(endmark, iend - 20)
    if iend < 0:
        raise Exception("Didn't find end of JPG!")

    istart += startfix
    iend += endfix
    print "JPG %d from %d to %d" % (njpg, istart, iend)
    jpg = pdf[istart:iend]
    # jpgfile = file("jpg%d.jpg" % njpg, "wb")
    # jpgfile.write(jpg)
    # jpgfile.close()
    im = Image.open(StringIO(jpg))
    # 过滤图像
    width, height = im.size
    box = (0, 140, width, height - 205)
    region = im.crop(box)

    im_sharp = region.filter(ImageFilter.SHARPEN)
    # 保存过滤过的图像到文件中
    im_sharp.save("jpg%d.jpg" % njpg, 'JPEG')

    njpg += 1
    i = iend
